package com.rpframework.website.device.act.api;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;
import com.rpframework.core.BaseAct;
import com.rpframework.core.utils.TagUtils;
import com.rpframework.utils.NumberUtils;
import com.rpframework.utils.Pager;
import com.rpframework.website.device.dao.IAddDao;
import com.rpframework.website.device.dao.IStreamDao;
import com.rpframework.website.device.domain.Add;
import com.rpframework.website.device.domain.Convert;
import com.rpframework.website.device.domain.Stream;
import com.rpframework.website.device.domain.User;
import com.rpframework.website.device.exception.APICodeException;
import com.rpframework.website.device.service.AddService;
import com.rpframework.website.device.service.IConvertService;
import com.rpframework.website.device.service.StreamService;
import com.rpframework.website.device.service.UserService;

/**
 * 商品模块接口
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/api/Convert")
public class ApiConvertAct extends BaseAct {
	@Resource IConvertService service;
	@Resource AddService AddService;
	@Resource StreamService StreamService;
	@Resource UserService userService;
	public @Resource IAddDao iDao;
	public @Resource IAddDao iAddDao;
	public	@Resource IStreamDao iStreamdao;
	
	
	@RequestMapping(value="/list",produces = "application/json; charset=utf-8")
	public @ResponseBody String listone(@RequestParam(value="pager",required = false ) Pager<Convert> pager,
//			@RequestParam(value="category",required = false ) String category,
//			@RequestParam(value="label",required = false ) String label,
//			@RequestParam(value="state",required = false ) String state,
//			@RequestParam(value="name",required = false ) String name,
			@RequestParam(value = "callback",required = false ) String callback,
			HttpSession session){
		User user = getSessionUser(session);
		if(user==null){
			throw new APICodeException(-4, "您尚未登录!");
		}
		
		if(pager==null){
			pager=new Pager<Convert>();
		}
//		if(StringUtils.isNotBlank(category))pager.getSearchMap().put("category", category);
//		if(StringUtils.isNotBlank(label))pager.getSearchMap().put("label", label);
//		if(StringUtils.isNotBlank(state))pager.getSearchMap().put("state", state);
//		if(StringUtils.isNotBlank(name))pager.getSearchMap().put("name", name);
		pager = service.getPager(pager);
		JsonObject json=new JsonObject();
		json.addProperty("totalPages", pager.getTotalPages());
		json.addProperty("currentPage", pager.getCurrentPage());
		json.addProperty("totalCount", pager.getTotalCount());
		json.addProperty("userConvert",user.getPoint() );
		List<Convert> list=pager.getItemList();
		if(list!=null && list.size()>0){
		JsonArray array=new JsonArray();
			for(Convert t : list){
				JsonObject obj = new JsonObject();
				obj.addProperty("id", t.getId());	
				obj.addProperty("name", t.getName());//商品名字
				JsonArray arr = new JsonParser().parse(t.getUrlList()).getAsJsonArray();//逗号分隔的json型的对象
				JsonArray a = new JsonArray();
				for(JsonElement li : arr){
					a.add(new JsonPrimitive(TagUtils.getFileFullPath(li.toString().replace("\"", ""))));
				}
				obj.add("urlList", a);
				obj.addProperty("converts", t.getConverts());//兑换积分值
				obj.addProperty("price", t.getPrice());//商品原价		
				obj.addProperty("stock", t.getStock());//商品库存		
				
				JsonArray arr1 = new JsonParser().parse(t.getDetList()).getAsJsonArray();//逗号分隔的json型的对象
				JsonArray a1 = new JsonArray();
				for(JsonElement li : arr1){
					a1.add(new JsonPrimitive(TagUtils.getFileFullPath(li.toString().replace("\"", ""))));
				}
				obj.add("detList", a1);//商品图片
				
				
				JsonArray arr2 = new JsonParser().parse(t.getLogoUrl()).getAsJsonArray();//逗号分隔的json型的对象
				JsonArray a2 = new JsonArray();
				for(JsonElement li : arr2){
					a2.add(new JsonPrimitive(TagUtils.getFileFullPath(li.toString().replace("\"", ""))));
				}
				obj.add("logoUrl", a2);//商品图片
				obj.addProperty("info", t.getInfo());//商品详情内容
				array.add(obj);
			}
			json.add("arrays", array);
		}
		if(StringUtils.isNotBlank(callback))return (callback + "(" + json + ")");
		return ""+json ;
	}	

	/**
	 * 商品详情 
	 * @param id
	 * @param callback
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/detail",produces = "application/json; charset=utf-8")
	public @ResponseBody String Detail(@RequestParam(value="id",required = false ) Integer id,
			@RequestParam(value = "callback",required = false ) String callback,
			HttpSession session){
		JsonObject json = new JsonObject();
		User user = getSessionUser(session);
		if(user==null){
			throw new APICodeException(-4, "您尚未登录!");
		}
		if(!NumberUtils.isValid(id)){
			throw new APICodeException(-4, "id为空！!");
		}
		Convert t = service.select(id);
		json.addProperty("id", t.getId());	
	
		
		
		json.addProperty("name", t.getName());//商品名字
		
		JsonArray arr = new JsonParser().parse(t.getLogoUrl()).getAsJsonArray();//逗号分隔的json型的对象
		JsonArray a = new JsonArray();
		for(JsonElement li : arr){
			a.add(new JsonPrimitive(TagUtils.getFileFullPath(li.toString().replace("\"", ""))));
		}
		json.add("logoUrl", a);
		JsonArray arr1 = new JsonParser().parse(t.getDetList()).getAsJsonArray();//逗号分隔的json型的对象
		JsonArray a1 = new JsonArray();
		for(JsonElement li : arr1){
			a1.add(new JsonPrimitive(TagUtils.getFileFullPath(li.toString().replace("\"", ""))));
		}
		json.add("delList", a1);
		JsonArray arr2 = new JsonParser().parse(t.getUrlList()).getAsJsonArray();//逗号分隔的json型的对象
		JsonArray a2 = new JsonArray();
		for(JsonElement li : arr2){
			a2.add(new JsonPrimitive(TagUtils.getFileFullPath(li.toString().replace("\"", ""))));
		}
		json.add("urlList", a2);
		

		json.addProperty("convert", t.getConverts());//兑换积分值
		json.addProperty("price", t.getPrice());//商品原价		
		json.addProperty("stock", t.getStock());//商品库存		
		json.addProperty("info", t.getInfo());//商品详情内容
		if(StringUtils.isNotBlank(callback))return (callback + "(" + json + ")");
		return ""+json ;
	}
	
	@RequestMapping(value="/add",produces = "application/json; charset=utf-8")
	public @ResponseBody String listone1(@RequestParam(value="pager",required = false ) Pager<Add> pager,
			@RequestParam(value="convertId",required = false ) Integer convertId,
			@RequestParam(value="name",required = false ) String name,
			@RequestParam(value="sex",required = false ) Integer sex,
			@RequestParam(value="tel",required = false ) String tel,
			@RequestParam(value="placeAdd",required = false ) String placeAdd,
			@RequestParam(value="add1",required = false ) String add1,
			@RequestParam(value = "callback",required = false ) String callback,
			HttpSession session){
		User user = getSessionUser(session);
		if(user==null){
			throw new APICodeException(-4, "您尚未登录!");
		}
		if(pager==null){
			pager=new Pager<Add>();
		}
		JsonObject json=new JsonObject();
		if(!NumberUtils.isNotValid(convertId)&&StringUtils.isNotBlank(name)
				&&!NumberUtils.isNotValid(sex)&&StringUtils.isNotBlank(tel)
				&&StringUtils.isNotBlank(placeAdd)&&StringUtils.isNotBlank(add1)){
			Add add = new Add();
			Convert t = service.select(convertId);
			add.setConvertName(t.getName());
			add.setUserId(user.getId());
			add.setConvertName(t.getName());
			add.setName(name);
			add.setSex(sex);
			add.setTel(tel);
			add.setPlaceAdd(placeAdd);
			add.setAdddz(add1);
			add.setCreateTime(System.currentTimeMillis()/1000);
			JsonObject obj = new JsonObject();
			int point=	user.getPoint();
			int jf = t.getConverts();
			int poin=point-jf;
			Boolean  flag=false;
			if(poin>=0){  flag = iDao.insert(add);}
			if(flag&&poin>=0){
				//添加积分增加流水
				Stream Stream = new Stream();
				Stream.setTitle("兑换礼品 ");
				Stream.setCreateTime(System.currentTimeMillis()/1000);
				Stream.setUserId(user.getId());
				Stream.setInfo("-"+jf);
				StreamService.insert(Stream);
				
				
				user.setPoint(poin);//修改积分
				userService.update(user);//提交数据
				obj.addProperty("code", 200);
				obj.addProperty("msg", "添加订单成功");
			}else{
				obj.addProperty("code", 500);
				obj.addProperty("msg", "添加订单失败");
				if(poin<0)
				obj.addProperty("msg", "积分不足");
			}
			json.add("arrays", obj);
			}
			else{
				throw new APICodeException(-6, "缺少参数!");
			}
		if(StringUtils.isNotBlank(callback))return (callback + "(" + json + ")");
		return ""+json ;
	}	
	/**
	 * 商品详情 
	 * @param id
	 * @param callback
	 * @param session
	 * @return
	 */
	@RequestMapping(value="/running",produces = "application/json; charset=utf-8")
	public @ResponseBody String running(@RequestParam(value="id",required = false ) Integer id,
			@RequestParam(value = "callback",required = false ) String callback,
			HttpSession session){
		JsonObject json = new JsonObject();
		User user = getSessionUser(session);
		if(user==null){
			throw new APICodeException(-4, "您尚未登录!");
		}
		List<Stream> list = iStreamdao.listStream(user.getId());
		json.addProperty("个人资料信息", "用户id,电话，昵称，头像，性别，积分，出生日期");	
		json.addProperty("id", user.getId());	
		json.addProperty("tel", user.getTel());	
		json.addProperty("nickName", user.getNickName());	
		json.addProperty("headImg", TagUtils.getFileFullPath(user.getHeadImg()));
		json.addProperty("sex", user.getSex());
		json.addProperty("point", user.getPoint());	
		json.addProperty("constellation", user.getConstellation());	
		
		
		JsonArray array=new JsonArray();
		for(Stream t:list){
			JsonObject obj = new JsonObject();
			obj.addProperty("id", t.getId());	
			obj.addProperty("userId", t.getUserId());	
			obj.addProperty("title", t.getTitle());	
			obj.addProperty("info", t.getInfo());	
			obj.addProperty("createTime", t.getCreateTime());	
			array.add(obj);
		}
	
		json.add("arrays", array);
		if(StringUtils.isNotBlank(callback))return (callback + "(" + json + ")");
		return ""+json ;
	}
}
